import Vue from 'vue'
import App from './App'

// 将数据存放本地缓存中
const set = (name, data) => {
	try {
		uni.setStorageSync(name, data)
	} catch (e) {
		console.log(e)
	}
}

// 从本地缓存中获取指定 name 对应的内容
const get = (name) => {
	let data
	try {
		data = uni.getStorageSync(name)
	} catch (e) {
		console.log(e)
	}
	return data
}

const remove = (name) => {
	let data
	try {
		data = uni.removeStorageSync(name)
	} catch (e) {
		console.log(e)
	}
	return data
}

const toUrl = (url) => {
	uni.navigateTo({
		url: url
	})
}
const toTab = (url) => {
	uni.switchTab({
		url: url
	})
}

const json = type=>{
	//模拟异步请求数据
	return new Promise(resolve=>{
		setTimeout(()=>{
			resolve(Json[type]);
		}, 200)
	})
}

const prePage = ()=>{
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	// #ifdef H5
	return prePage;
	// #endif
	return prePage.$vm;
}

//删除指定的某个对象元素
const delArrayObj = (_arr,_obj)=>{
	var length = _arr.length;
	for(var i = 0; i < length; i++){
		if(_arr[i] == _obj){
			if(i == 0){
				_arr.shift(); //删除并返回数组的第一个元素
				return;
			}else if(i == length-1){
				_arr.pop();  //删除并返回数组的最后一个元素
				return;
			}else{
				_arr.splice(i,1); //删除下标为i的元素
				return;
			}
		}
	}
}

//移动指定的某个对象元素 到最前面
const removBehandArrayObj = (_arr,_obj)=>{
	var length = _arr.length;
	for(var i = 0; i < length; i++){
		if(_arr[i] == _obj){
			_arr.splice(i,1); //删除下标为i的元素
			_arr.unshift(_obj); //添加下标为i的元素到最前面
			return;
		}
	}
}

const formatRichText = (html) => {
	let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
		return match;
	});
	newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	newContent = newContent.replace(/\<img/gi, '<img style="width:100%;height:auto;display:inline-block;"');
	return newContent;
}

const shareList = [{
		type: 1,
		icon: '/static/images/share_wechat.png',
		text: '微信好友'
	},
	{
		type: 2,
		icon: '/static/images/share_moment.png',
		text: '朋友圈'
	}
]

Vue.config.productionTip = false

//接口请求挂载vue原型
import Httprequest from './utils/Httprequest'
Vue.prototype.$http = Httprequest

//提示框
import helper from './utils/helper'
Vue.prototype.$helper = helper

//存储状态
import store from './store/index.js'
Vue.prototype.$store = store

// #ifdef H5
import wechat from './utils/wechat.js'
if(wechat.isWechat()){
    Vue.prototype.$wechat = wechat;
}
// #endif


Vue.prototype.$api = {
	set,
	get,
	remove,
	toUrl,
	toTab,
	prePage,
	delArrayObj,
	removBehandArrayObj,
	shareList,
	formatRichText
};

App.mpType = 'app'

const app = new Vue({
	store,
    ...App
})
app.$mount()